package com.lianyu507.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import com.lianyu507.pojo.MbUser;
import com.lianyu507.pojo.MbUserExample;
import com.lianyu507.service.MbUserService;
import com.lianyu507.util.DataUtil;

import com.lianyu507.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.stereotype.Service;

import com.lianyu507.service.RegisterValidateService;


import javax.mail.internet.MimeMessage;


@Service
public class RegisterValidateServiceImpl implements RegisterValidateService {



	@Autowired
	private MbUserService mbUserService;

	private static final  long EMAIL_VALID_TIME=2;  
	
	// 简单值的注入
		@Value("${mail.applicationUrl}")
		private String applicationUrl;
		@Value("${mail.host}")
		private String host;
		@Value("${mail.username}")
		private String username;
		@Value("${mail.password}")
		private String password;
		/**
		 * 绑定邮箱的实现
		 */
		public void bindEmail(String token) {
			// 根据token查询当前用户
			MbUserExample mbUserExample=new MbUserExample();
			MbUserExample.Criteria criteria = mbUserExample.createCriteria();
			criteria.andTokenEqualTo(token);

			List<MbUser> userList = mbUserService.selectByExample(mbUserExample);

			//mbUserExample.createCriteria().andTokenEqualTo(token);
			//List<MbUser> mbUsers = mbUserService.selectByExample(mbUserExample);


			//验证信息过期
			if (userList != null && DataUtil.getBetweenSecond(userList.get(0).getCreateTime(), new Date()) > EMAIL_VALID_TIME) {
				MbUser user = userList.get(0);
				user.setStatus(new Byte("2"));
				mbUserService.updateByExample(user,null);
				throw  new RuntimeException("验证已经过期，请从新注册");
			}
			//用户是否为空&&s是否过期
			if (userList != null && DataUtil.getBetweenSecond(userList.get(0).getCreateTime(), new Date()) < EMAIL_VALID_TIME) {
				// 判断是否在有效期内
				// 用户如果用户没有绑定邮箱
				MbUser user = userList.get(0);
				if (user.getStatus()==0) {
					// 添加邮箱状态码 设置state为绑定状态
					user.setStatus(new Byte("1"));
					user.setUpdateTime(new Date());
			//		mbUserMapper.updateByPrimaryKey(user);//更新用户信息
					mbUserService.updateByPrimaryKey(user);
					return;
				}
			} else {
				//绑定失败改变状态为删除状态
				MbUser user = userList.get(0);
				user.setStatus(new Byte("2"));
				mbUserService.updateByExample(user,null);
				throw new RuntimeException("验证邮箱地址错误!");
			}

		}

		/*
		 * 使用邮箱注册账户
		 */
		public void sendVerifyEmail(String email,String username,String password) {
			// TODO Auto-generated method stub
			MbUserExample example = new MbUserExample();
			MbUserExample.Criteria criteria = example.createCriteria();
			criteria.andUserEmailEqualTo(email).andUserNameEqualTo(username);

			List<MbUser> userList = mbUserService.selectByExample(example);
			// 0是未激活状态，1是激活状态，2是过期或删除
             if (userList.get(0) != null  && userList.get(0).getStatus() == 2){
             	throw new RuntimeException("验证时间过期或是被用户被删除");
			 }
			 if ( userList.get(0) != null && userList.get(0).getStatus() == 1) {
             	throw new RuntimeException("用户已经被注册");
			}if (userList.get(0) == null || userList.get(0).getStatus() == 2) {
				//生成token
				String token = UUID.randomUUID().toString();
				//邮箱内容
				StringBuffer content = new StringBuffer();
				// 构造邮件信息内容并发送
				content.append("<html><head></head><body><h1>验证邮件请点击,<a href='").append(applicationUrl).append("bindEmail?token=").append(token)
						.append("'>这里</a>,有效期是").append(EMAIL_VALID_TIME).append("小时!</h1></body></html>");

				try {
					//发送邮件
					sendEmai(email, content.toString());
					System.err.println("发送成功.............");
					//绑定验证码并把状态值设为未绑定状态

					//添加未绑定邮箱用户
					MbUser user=new MbUser();
					user.setStatus(new Byte("0"));
					user.setUserEmail(email);
					user.setCreateTime(new Date());
					user.setToken(token);
					user.setUserName(username);
					user.setUserPassword(MD5.encode(password));
					mbUserService.insert(user);

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					throw new RuntimeException("发送邮件失败");
				}
			}
		}

		private void sendEmai(String email,String content) throws Exception {
			//发送html邮件
			JavaMailSenderImpl sender= new JavaMailSenderImpl();
			//设置服务器地址
			sender.setHost(host);
			//创建一个邮件信息
			MimeMessage mimeMessage = sender.createMimeMessage();
			MimeMessageHelper messageHelper=new MimeMessageHelper(mimeMessage,"utf-8");
			//设置收件人 寄件人 等邮件相关信息
			messageHelper.setTo(email);
			messageHelper.setFrom(username);
			messageHelper.setSubject("绑定邮箱验证邮件");
			//设置邮件内容//true表示启动html格式邮件
			messageHelper.setText(content,true);
			//设置发送准备
			sender.setUsername(username);
			sender.setPassword(password);
			Properties prop =  new Properties() ;
			//设置为true 让服务器进行认证账户和密码是否正确
			prop.put("mail.smtp.auth",true) ;
			prop.put("mail.smtp.timeout", "25000") ;
			prop.put("mail.smtp.port", "25");
			prop.put("mail.smtp.starttls.enable", "true");
		     //prop.put("mail.smtp.host", host);
			sender.setJavaMailProperties(prop);
			//发送邮件 
			sender.send(mimeMessage);
		}
		

	
	
}
